package com.jokerpan.project.util;

import org.apache.http.impl.client.CloseableHttpClient;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * HttpClient连接池工厂<br/>
 */
public class GlobalHttpClientConnectionManagerFactory {
    /**
     * 超时参数
     */
    public static final long timeToLive = 10;
    /**
     * 超时参数单位
     */
    public static final TimeUnit tunit = TimeUnit.SECONDS;
    /**
     * 设置整个连接池最大连接数
     */
    public static final int maxTotal = 256;
    /**
     * 单个路由最大连接数
     */
    public static final int defaultMaxPerRoute = 256;

    public static Map<String, GlobalHttpClientConnectionManager> cache = new ConcurrentHashMap<>();

    public static GlobalHttpClientConnectionManager getGlobalHttpClientConnectionManager(String key) {
        return getGlobalHttpClientConnectionManager(key, timeToLive, tunit, maxTotal, defaultMaxPerRoute);
    }

    public static GlobalHttpClientConnectionManager getGlobalHttpClientConnectionManager(String key, long timeToLive, TimeUnit tunit, int maxTotal, int defaultMaxPerRoute) {
        GlobalHttpClientConnectionManager manager = cache.get(key);
        if (null == manager) {
            synchronized (cache) {
                manager = cache.get(key);
                if (null == manager) {
                    manager = new GlobalHttpClientConnectionManager(timeToLive, tunit, maxTotal, defaultMaxPerRoute);
                    cache.put(key, manager);
                }
            }
        }
        return manager;
    }

    public static CloseableHttpClient getCloseableHttpClient(String key) {
        return getCloseableHttpClient(key, timeToLive, tunit, maxTotal, defaultMaxPerRoute);
    }

    public static CloseableHttpClient getCloseableHttpClient(String key, long timeToLive, TimeUnit tunit, int maxTotal, int defaultMaxPerRoute) {
        return getGlobalHttpClientConnectionManager(key, timeToLive, tunit, maxTotal, defaultMaxPerRoute).getHttpClient();
    }
}